package top.appx.easysql;

import top.appx.easysql.data.DataTable;

import java.sql.SQLException;
import java.util.List;

/**
 * Created by 燎火 on 2015/10/10.
 */
public abstract class BaseDBHelper {
    /**
     * 创建Database对象,但不打开
     *
     * @return
     */
    public abstract BaseDatabase createDataBase();

    /**
     * 执行sql更新语句
     *
     * @param sql
     * @param paramValues
     * @return
     */
    public int execute(String sql, Object... paramValues) {
        BaseDatabase db = null;
        try {
            db = createDataBase();
            return db.execute(sql, paramValues);
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    /**
     * 执行查询返回结果
     * @param sql
     * @param paramValues
     * @return
     */
    public DataTable queryDataTable(String sql, Object... paramValues) {
        BaseDatabase db = null;
        try {
            db = createDataBase();
            return db.queryDataTable(sql, paramValues);
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    /**
     * 查询并返回实体对象对象集合
     *
     * @param entityClass 根据这个类的Table注解得到表名,默认表名为类名
     * @param restrains
     * @return
     */
    public <T> List<T> query(Class<T> entityClass, Restrain... restrains) {
        BaseDatabase db = null;
        try {
            db = createDataBase();
            return db.query(entityClass, restrains);
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    /**
     * 根据sql语句查询出实体对象集合
     *
     * @param entityClass
     * @param sql
     * @param paramValues
     * @return
     * @throws Exception
     */
    public <T> List<T> queryBySql(Class<T> entityClass, String sql, Object... paramValues) throws Exception {
        BaseDatabase db = null;
        try {
            db = createDataBase();
            return db.queryBySql(entityClass, sql, paramValues);
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }


}
